import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入store
import store from '@/store'

// 导入路由组件
const Reg = () => import('@/views/Reg.vue')
const Login = () => import('@/views/Login.vue')
const Main = () => import('@/views/Main.vue')
// 导入子路由
const Home = () => import('@/views/Menus/home.vue')
const UserInfo = () => import('@/views/Menus/User/Info.vue')
const UserAvatar = () => import('@/views/Menus/User/Avatar.vue')
const UserPwd = () => import('@/views/Menus/User/Pwd.vue')
const CateList = () => import('@/views/Menus/Article/List.vue')
const ArtList = () => import('@/views/Menus/Article/ArtList.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  // 路由规则
  routes: [
    // 注册页的路由规则
    { path: '/reg', component: Reg },
    // 登录页的路由规则
    { path: '/login', component: Login },
    // 后台主页的路由规则
    {
      path: '/',
      component: Main,
      redirect: '/home',
      // 子路由规则
      children: [
        { path: 'home', component: Home },
        { path: 'user-info', component: UserInfo },
        { path: 'user-avatar', component: UserAvatar },
        { path: 'user-pwd', component: UserPwd },
        { path: 'art-cate', component: CateList },
        { path: 'art-list', component: ArtList }
      ]
    }
  ]
})

// 导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/') {
    // console.log(store)
    const token = store.state.user.token
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
